package com.ybear.ybhotrepair.utils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.reflect.Field;

public class FieldUtils {
    /**
     * 获取指定的属性成员
     * @param obj       待获取的对象
     * @param cls       待获取的类
     * @param field     类中的成员名称
     * @return          获取到的成员
     */
    @Nullable
    public static Object getField(@Nullable Object obj,
                                  @Nullable Class<?> cls,
                                  @Nullable String field) {
        if( obj == null || cls == null || field == null ) return null;
        Field f = getField(cls, field);
        try {
            return f == null ? null : f.get( obj );
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Nullable
    public static Field getField(@NonNull Class<?> cls, @NonNull String field) {
        Field f = null;
        try {
            //获取指定属性成员
            f = cls.getDeclaredField( field );
            //允许访问
            f.setAccessible( true );
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return f;
    }

    /**
     * 设置指定对象的属性成员
     * @param fromObj       待设置的对象
     * @param fromCls       待设置的类
     * @param fromField     待设置的属性成员
     * @param toObj         设置的对象
     * @return              设置结果
     */
    public static boolean setField(@Nullable Object fromObj,
                             @Nullable Class<?> fromCls, @Nullable String fromField,
                             @Nullable Object toObj) {
        if( fromObj == null || fromCls == null || fromField == null || toObj == null ) return false;
        Field f = getField(fromCls, fromField);
        if( f == null ) return false;
        try {
            f.set(fromObj, toObj);
            return true;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}
